<template>
  <div class="scroll-up">
    <div ref="scroller" class="scroll-up-container" @scroll="onScroll">
      <div class="scroll-up-content">
        <slot name="default"></slot>
      </div>
      <div class="scroll-up-footer">
        <slot name="footer">
          <div class="scroll-up-footer-default">
            <mu-circular-progress v-show="loading" :size="30"></mu-circular-progress>
            <p class="scroll-up-text">{{ text }}</p>
          </div>
        </slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScrollUp',
  props: {
    hasMore: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    triggerOffset: {
      type: Number,
      default: 5
    },
    loadingText: {
      type: String,
      default: '加载中'
    },
    loadMoreText: {
      type: String,
      default: '上拉加载更多'
    },
    noMoreText: {
      type: String,
      default: '没有更多数据了'
    }
  },
  computed: {
    text() {
      if (this.hasMore) {
        return this.loading ? this.loadingText : this.loadMoreText
      } else {
        return this.noMoreText
      }
    }
  },
  methods: {
    onScroll() {
      if (this.loading || !this.hasMore) {
        return
      }
      const { scrollTop, scrollHeight, offsetHeight } = this.$refs.scroller
      const move = scrollHeight - scrollTop
      const remain = move - offsetHeight
      if (remain < this.triggerOffset) {
        this.$refs.scroller.scrollTop = scrollTop - this.triggerOffset
        this.$emit('load')
      }
    }
  }
}
</script>

<style scoped>
.scroll-up {
  overflow: hidden;
  width: 100%;
  height: 100%;
}
.scroll-up-container {
  overflow-y: scroll;
  width: 100%;
  height: 100%;
}
.scroll-up-footer-default {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
}
.scroll-up-text {
  padding: 0 12px;
}
</style>
